package com.dykj.fireFighting.web.app;

import com.dykj.fireFighting.api.base.dev.entity.DevHisFiles;
import com.dykj.fireFighting.api.base.dev.service.IDevHisFilesService;
import com.dykj.fireFighting.api.base.devHisResult.service.IDevHisResultService;
import com.dykj.fireFighting.api.base.effecttimesetting.service.IEffectiveTimeSettingService;
import com.dykj.fireFighting.api.base.effecttimesetting.vo.EffectiveTimeSettingVo;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.file.entity.DataFiles;
import com.dykj.fireFighting.api.elasticsearch.devHis.entity.EsDevHis;
import com.dykj.fireFighting.api.elasticsearch.devHis.service.EsDevHisService;
import com.dykj.fireFighting.api.socialUnit.devHis.dto.AlarmRecordDto;
import com.dykj.fireFighting.api.socialUnit.devHis.dto.DevHisDto;
import com.dykj.fireFighting.api.socialUnit.devHis.entity.AlarmRecord;
import com.dykj.fireFighting.api.socialUnit.devHis.entity.DevHis;
import com.dykj.fireFighting.api.socialUnit.devHis.service.IDevHisService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: zly
 * @Description : 火警复核
 * @Date: 2021-07-05
 */
@Slf4j
@Api(value = "火警复核app接口", tags = {"火警复核app接口"})
@RestController
@RequestMapping("/app/devHisAlarm")
public class AppDevHisAlarmController {

    @DubboReference
    private IDevHisService devHisService;
    @DubboReference
    private IDevHisFilesService devHisFilesService;
    @DubboReference
    private IEffectiveTimeSettingService effectiveTimeSettingService;
    @DubboReference
    private IEnterpriseService enterpriseService;
    @DubboReference
    private IDevHisResultService devHisResultService;
    @DubboReference
    private EsDevHisService esDevHisService;


    /**
     * 实时报警接口记录列表
     *
     * @return
     */
    @AutoLog(value = "实时报警接口-分页列表查询")
    @ApiOperation(value = "实时报警接口-分页列表查询", notes = "实时报警接口-分页列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "deviceCode", value = "用户传输装置唯一编码", dataType = "String", required = false),
            @ApiImplicitParam(paramType = "query", name = "bjzt", value = "部件状态id", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "page", value = "页码", dataType = "Integer", required = true),
            @ApiImplicitParam(paramType = "query", name = "limit", value = "每页数据条数", dataType = "Integer", required = true),
            @ApiImplicitParam(paramType = "query", name = "status", value = "状态(0未复核1已复核)", dataType = "String", required = true)
    })
    @GetMapping("/list")
    /* @RequiresPermissions("app/devHisAlarm/list")*/
    public CommonResult queryList(DevHisDto devHisDto,   @RequestParam(required = false, defaultValue = "1") Integer page,
                                  @RequestParam(required = false, defaultValue = "10") Integer limit) {

        String unitId = ShiroUtil.getUser().getEnterpriseId().toString();
        PageVo<EsDevHis> esDevHisPageVo = esDevHisService.queryList(devHisDto.getSj(), devHisDto.getBjzt(), devHisDto.getStatus(), null, unitId,
                page - 1, limit,devHisDto.getDevName(),devHisDto.getDevType(),devHisDto.getLx());

        List<EsDevHis> list = esDevHisPageVo.getList();
        if (!CollectionUtils.isEmpty(list)) {
            List<EsDevHis> relationIdList = new ArrayList<>();
            list.stream().forEach(esDevHis -> {
                if (StringUtils.isNotBlank(esDevHis.getRelationId())) {
                    DevHis devHis = devHisService.queryByRelationId(esDevHis.getRelationId());
                    if (devHis != null) {
                        esDevHis.setDevUnitName(devHis.getDevUnitName());
                        esDevHis.setDevName(devHis.getDevName());
                        esDevHis.setDevType(devHis.getDevType());
                    }
                }
                relationIdList.add(esDevHis);
            });
            esDevHisPageVo.setList(relationIdList);
        }
        return CommonResult.success(esDevHisPageVo);
    }

    /**
     * app报警信息列表
     *
     * @return
     */
    @AutoLog(value = "报警信息-分页列表查询")
    @ApiOperation(value = "报警信息-分页列表查询", notes = "实时报警接口-分页列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "page", value = "页码", dataType = "Integer", required = true),
            @ApiImplicitParam(paramType = "query", name = "limit", value = "每页数据条数", dataType = "Integer", required = true)
    })
    @GetMapping("/alarmList")
    /* @RequiresPermissions("app/devHisAlarm/list")*/
    public CommonResult<PageVo<AlarmRecord>> queryAlarmList(AlarmRecordDto alarmRecordDto) {
        Long enterpriseId = ShiroUtil.getUser().getEnterpriseId();
        alarmRecordDto.setUnitId(enterpriseId + "");
        PageVo<AlarmRecord> alarmRecordPageVo = devHisService.queryAlarmList(alarmRecordDto);
        return CommonResult.success(alarmRecordPageVo);
    }

    /**
     * 复核
     *
     * @param devHis
     * @return
     */
    @AutoLog(value = "实时报警接口-复核")
    @ApiOperation(value = "实时报警接口-复核", notes = "实时报警接口-复核")
    @PostMapping("/update")
    public CommonResult update(@Valid @RequestBody DevHis devHis) {
        try {

            DevHis his = devHisService.getDevHisById(devHis.getId());
            if (null == his) {
                return CommonResult.failed("无记录");
            }
            //UpTime是上传时间
            Date upTime = his.getUpTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(upTime);
            LoginUserVo user = ShiroUtil.getUser();
            Enterprise enterprise = enterpriseService.getInfoByBindingCode(user.getBindingCode());
            EffectiveTimeSettingVo effectiveTimeSettingVo = effectiveTimeSettingService.isEffective(upTime, "fireAlarm", enterprise.getId().toString());
            if (null != effectiveTimeSettingVo) {
                if (effectiveTimeSettingVo.getIsEffective()) {
                    devHis.setIsEffective(1);
                    devHisResultService.saveOne(4, user.getEnterpriseId().toString(),format);
                } else {
                    devHis.setIsEffective(0);
                }
            } else {
                return CommonResult.success("有效时间失误");
            }
            Date date=new Date();
            devHis.setStatus("1");
            devHis.setFuheTime(date);
            devHis.setFuhePersonId(user.getId().toString());
            devHis.setFuhePerson(user.getLoginName());
            String imgFiles = devHis.getImgFiles();
            if (null != imgFiles && StringUtils.isNotBlank(imgFiles)) {
                List<String> imgFilesList = Arrays.asList(imgFiles.split(","));
                for (String imgFile : imgFilesList) {
                    DevHisFiles devHisFiles = new DevHisFiles();
                    devHisFiles.setId(UUIDUtils.get32UUID());
                    devHisFiles.setDevhisId(devHis.getId().toString());
                    devHisFiles.setFiledId(imgFile);
                    devHisFiles.setSpareFiled("3");
                    devHisFiles.setTableName(devHis.getTableName());
                    devHisFilesService.insert(devHisFiles);
                }
            }
            EsDevHis esDevHis = new EsDevHis();
            BeanUtils.copyProperties(devHis, esDevHis);
            esDevHis.setFuheTime(sdf1.format(date));
            devHisService.updateAndInsertImg(devHis);
            esDevHisService.updateEsDevHis(esDevHis);
            devHisResultService.saveOne(5, user.getEnterpriseId().toString(),format);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//contoller中增加事务
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 获取图片
     */
    @AutoLog(value = "实时报警接口-获取复核图片")
    @ApiOperation(value = "实时报警接口-获取复核图片", notes = "实时报警接口-获取复核图片")
    @GetMapping("/getImgs/{id}")
    public CommonResult getImgs(@PathVariable("id") String id) {
        try {

            String tableType = "3";
            List<DataFiles> filesList = devHisFilesService.getImgsByHisId(id, tableType, "");
            return CommonResult.success(filesList);
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("查询失败，请联系管理员");
        }
    }

}
